import hashlib
import random
import uuid
from django.db import models, IntegrityError
from django.utils.text import slugify

from apps.common.models import Options, PbiBaseCheck, OpocBaseModel, OpocBaseModelNew
from extensions.common.base import *
from extensions.models import *


class Opoc_Certificate_Imgs(OpocBaseModel):
    """一人一码个人证书Img"""
    company = ForeignKey('system.Company', on_delete=CASCADE,null=True, blank=True, default=1,
                         related_name='Opoc_Certificate_Imgs')
    file = ImageField(upload_to='opoc_certificate_imgs/',verbose_name='图片文件')
    name = CharField(max_length=256, verbose_name='文件名称')
    type = IntegerField(verbose_name='文件类型')#1=登高2=电工3=安全员4=其它
    filled_by = ForeignKey('system.User', on_delete=SET_NULL,null=True, blank=True, default=None,
                           related_name='Opoc_Certificate_Imgs')  # 支填报人
    add_time = DateTimeField(auto_now_add=True, verbose_name='创建时间', null=True, blank=True)


class Common_Pdfs(OpocBaseModel):
    """一人一码通用pdf"""
    company = ForeignKey('system.Company', on_delete=CASCADE, blank=True, default=None,
                         related_name='Common_Pdfs')
    file = FileField(max_length=256, upload_to='opoc_common_pdf/',verbose_name='文件')
    name = CharField(max_length=256, verbose_name='文件名称')
    type = IntegerField(verbose_name='文件类型')#1 0=合同2=保险 1 3=安全责任书 2 4=岗前教育培训 3 5=项目启动前的安全技术交底 46=服务订单工单 5 7=任务单派发 6
    filled_by = ForeignKey('system.User', on_delete=SET_NULL,null=True, blank=True, default=None,
                           related_name='Common_Pdfs')  # 支填报人
    add_time = DateTimeField(auto_now_add=True, verbose_name='创建时间', null=True, blank=True)


# 一人一码基础信息
class Opoc_Records(OpocBaseModelNew):
    # 组织机构信息

    company = ForeignKey('system.Company', on_delete=CASCADE, blank=True, default=None,related_name='Opoc_Records')
    sfz_number = CharField(max_length=255,unique=True, verbose_name='身份证号码', null=True, blank=True)
    phone = CharField(max_length=255, verbose_name='联系电话', null=True, blank=True)
    status = IntegerField(verbose_name='人员状态', null=True, blank=True)#1=参工2=待工-1=离职
    # ascription = IntegerField(verbose_name='归属劳务单位', null=True, blank=True)#1=比选+短名单2=综合劳务3=招募+二次甄选
    ascription = JSONField(verbose_name='归属劳务单位', null=True,default=[], blank=True)#1=比选+短名单2=综合劳务3=招募+二次甄选
    labor_service_unit = ForeignKey('opoc.Labor_service_unit', on_delete=SET_NULL,null=True, blank=True, default=None,related_name='Opoc_Records')
    # labor_service_unit = ManyToManyField('opoc.Labor_service_unit', null=True, blank=True, default=None,related_name='Opoc_Records')
    # team_attribute = IntegerField(verbose_name='队伍属性', null=True, blank=True)#1=架子队+短名单2=市州工程队3=区县工程队4=劳务单位施工队
    team_attribute = JSONField(verbose_name='队伍属性', null=True,default=[], blank=True)#1=架子队+短名单2=市州工程队3=区县工程队4=劳务单位施工队
    certificate_holding = JSONField(verbose_name='持证情况', null=True, default=[],blank=True)
    contract_signing_begin_date = DateField(verbose_name='签订日期', null=True, blank=True)
    contract_signing_end_date = DateField(verbose_name='截止日期', null=True, blank=True)
    insurance_limit = FloatField(verbose_name='保额', null=True, blank=True)
    insurance_effective_date = DateField(verbose_name='保险购买生效日', null=True, blank=True)
    insurance_invalid_date = DateField(verbose_name='保险购买失效日', null=True, blank=True)
    is_safety_responsibility = BooleanField(verbose_name='与劳务单位安全责任书签订', default=False)
    project_name = CharField(max_length=255, verbose_name='实施项目名称', null=True, blank=True)
    is_safety_education = BooleanField(verbose_name='上岗前的安全教育培训及考核', default=False)
    is_monthly_safety_education = BooleanField(verbose_name='月度安全教育培训', default=False)
    is_service_order = BooleanField(verbose_name='服务订单工单派发', default=False)
    is_task_dispatch = BooleanField(verbose_name='任务单派发', default=False)
    is_safety_disclosure = BooleanField(verbose_name='项目启动安全技术交底', default=False)
    other_conditions  = CharField(max_length=255, verbose_name='其他需要说明的情况', null=True, blank=True)
    climb_high_img  = ForeignKey(Opoc_Certificate_Imgs, on_delete=SET_NULL,null=True, blank=True, default=None,related_name='Opoc_Records_climb_high_Img')  # 登高证
    electrician_img  = ForeignKey(Opoc_Certificate_Imgs, on_delete=SET_NULL, null=True,blank=True, default=None,related_name='Opoc_Records_electrician_Img')  # 电工证
    safety_officer_img  = ForeignKey(Opoc_Certificate_Imgs, on_delete=SET_NULL, null=True,blank=True, default=None,related_name='Opoc_Records_safety_officer_Img')  # 安全员证
    other_person_img  = ForeignKey(Opoc_Certificate_Imgs, on_delete=SET_NULL, null=True,blank=True, default=None,related_name='Opoc_Records_other_person_Img')  # 个人其它证
    construction_contract_pdf = ForeignKey(Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,related_name='Opoc_Records_construction_contract_pdf')  # 合同
    insurance_pdf = ForeignKey(Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,related_name='Opoc_Records_insurance_pdf')  # 保险
    safety_responsibility_pdf = ForeignKey(Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,related_name='Opoc_Records_safety_responsibility_pdf')  # 安全责任书
    safety_education_pdf = ForeignKey(Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,related_name='Opoc_Records_safety_education_pdf')  # 岗前教育培训
    safety_disclosure_pdf = ForeignKey(Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,related_name='Opoc_Records_safety_disclosure_pdf')  # 项目启动前的安全技术交底
    # service_order_pdf = ForeignKey(Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,related_name='Opoc_Records_service_order_pdf')  # 服务订单工单
    # task_dispatch_pdf = ForeignKey(Common_Pdfs, on_delete=SET_NULL, null=True, blank=True, default=None,related_name='Opoc_Records_task_dispatch_pdf')  # 任务单
    service_order_pdf = ManyToManyField(Common_Pdfs, null=True, blank=True, default=None,related_name='Opoc_Records_service_order_pdf')  # 服务订单工单
    task_dispatch_pdf = ManyToManyField(Common_Pdfs, null=True, blank=True, default=None,related_name='Opoc_Records_task_dispatch_pdf')  # 任务单

    filled_by = ForeignKey('system.User', on_delete=SET_NULL,null=True, blank=True, default=None,related_name='Opoc_Records')  # 支填报人
    # step = IntegerField(verbose_name='填报步骤', null=True, blank=True)
    # next_checker = ForeignKey('system.User', on_delete=SET_NULL, null=True, blank=True, default=None,
    #                           related_name='opoc_next_checker')  # 下一步审核或操作的人
    # check_records = ManyToManyField('opoc.OpocCheck', blank=True, null=True,related_name='Opoc_Records',verbose_name='审核记录')  # 审核记录
    is_effective = IntegerField(default=0, null=True, blank=True, verbose_name='是否生效')#1=已生效0=未生效-1=退回修改
    add_time = DateTimeField(auto_now_add=True, verbose_name='创建时间',null=True, blank=True)

    # 1 0=合同2=保险 1 3=安全责任书 2 4=岗前教育培训 3 5=项目启动前的安全技术交底 46=服务订单工单 5 7=任务单派发 6
    def __str__(self):
        return self.name

    def generate_unique_id(self):
        unique_id = random.randint(10 ** 9, 10 ** 10 - 1)
        while Opoc_Records.objects.filter(id=unique_id).exists():
            unique_id = random.randint(10 ** 9, 10 ** 10 - 1)
        return unique_id

    def generate_slug(self):
        # 使用UUID生成一个唯一的字符串，并转换为slug格式
        unique_slug = str(uuid.uuid4()).replace("-", "")
        while Opoc_Records.objects.filter(slug=unique_slug).exists():
            unique_slug = str(uuid.uuid4()).replace("-", "")
        return unique_slug


# 检查记录表
class Opoc_InspectionRecord(models.Model):
    inspection_location = models.CharField(max_length=255, verbose_name='检查地点')
    inspector = models.ForeignKey('system.User', on_delete=models.CASCADE,blank=True, null=True)
    content = models.TextField(blank=True, null=True, verbose_name='检查内容')
    problem = models.TextField(blank=True, null=True, verbose_name='发现问题')
    opoc_record = models.ForeignKey(Opoc_Records, on_delete=models.CASCADE, related_name='Opoc_InspectionRecord')
    longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True)  # 经度
    latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True)#纬度
    remarks = CharField(max_length=255, null=True, blank=True, verbose_name='备注')
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.opoc_record} - {self.inspector}"

# 检查记录图片
class Opoc_InspectionPhoto(models.Model):
    company = ForeignKey('system.Company', on_delete=CASCADE, blank=True, default=None,
                         related_name='Opoc_InspectionPhoto')
    opoc_inspectionRecord = ForeignKey(Opoc_InspectionRecord, on_delete=CASCADE, blank=True, default=None,
                         related_name='Opoc_InspectionPhoto')
    file = models.ImageField(upload_to='opoc_inspection_photos/')
    name = CharField(max_length=256, null=True, verbose_name='图片名称')
    filled_by = ForeignKey('system.User', on_delete=SET_NULL, null=True, blank=True, default=None,
                           related_name='Opoc_InspectionPhoto')  # 填报人
    add_time = DateTimeField(auto_now_add=True, verbose_name='创建时间', null=True, blank=True)

    def __str__(self):
        return self.file.name

# 临时检查记录图片
class Opoc_InspectionPhoto_temp(models.Model):
    file = models.ImageField(upload_to='opoc_inspection_photos_temp/')
    name = CharField(max_length=256, null=True, verbose_name='图片名称')

    def __str__(self):
        return self.file.name

class Labor_service_unit(OpocBaseModel):
    company = ForeignKey('system.Company', on_delete=CASCADE, blank=True, default=None, related_name='Labor_service_unit')
    filled_by = ForeignKey('system.User', on_delete=SET_NULL, null=True,blank=True, default=None,
                           related_name='Labor_service_unit')  # 支填报人
    class Meta:
        verbose_name = '劳务单位'


__all__ =[
    'Opoc_Records',
    'Opoc_Certificate_Imgs',
    'Common_Pdfs',
    'Labor_service_unit',
]
